package com.android.lovely

import android.app.Activity
import android.app.Application
import android.os.Build
import android.os.Bundle
import android.os.StatFs
import android.util.Log
import coil.ComponentRegistry
import coil.ImageLoader
import coil.ImageLoaderFactory
import coil.decode.GifDecoder
import coil.decode.ImageDecoderDecoder
import coil.disk.DiskCache
import coil.memory.MemoryCache
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustConfig
import com.adjust.sdk.AdjustEvent
import com.android.billingclient.api.Purchase
import com.android.lovely.aav.PreferentialManager
import com.android.lovely.aav.lifecycle.LovelyLifecycleManager
import com.android.lovely.admob.AdmobManager
import com.android.lovely.api.service.systemService
import com.android.lovely.data.Language
import com.android.lovely.data.deviceLanguage
import com.android.lovely.data.getLanguages
import com.android.lovely.manager.KVStore
import com.android.lovely.manager.LanguageManager.changeAppLanguage
import com.android.lovely.user.UserManager
import com.android.lovely.util.MMKVUtils
import com.facebook.appevents.AppEventsLogger
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.crashlytics.internal.model.CrashlyticsReport.Session.User
import com.google.firebase.messaging.FirebaseMessaging
import com.kotlin.extensions.app.BaseApplication
import com.kotlin.extensions.appContext
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.coroutine.applicationScope
import com.tencent.mmkv.MMKV
import io.glassfy.androidsdk.GooglePlayManager
import io.glassfy.androidsdk.delegate.PurchaseDelegate
import io.glassfy.androidsdk.model.PurchaseParams
import kotlinx.coroutines.delay
import java.io.File
import java.math.BigDecimal
import java.util.Currency
import java.util.Stack

/**
 *
 * @author why
 * @date 2025/3/6 14:09
 */
class LovelyApplication : BaseApplication(), PurchaseDelegate, ImageLoaderFactory {
    override fun initOnMainProgress() {
        registerActivityLifecycleCallbacks(LifecycleApplication)
//        MMKVUtils.instance.init(appContext)
        MMKV.initialize(appContext)
        changeAppLanguage(this, KVStore.appLanguage.code)
        GooglePlayManager.setReportDelegate(this)
        GooglePlayManager.init(this)
        AdmobManager.init()
        GoogleRefer.init()
        initLanguage()
        initAdjust()
        LovelyLifecycleManager.init()
        PreferentialManager.init()
    }

    private fun initAdjust() {
        val appToken = "{YourAppToken}"
        val environment = AdjustConfig.ENVIRONMENT_SANDBOX
        val config = AdjustConfig(this, appToken, environment)
        Adjust.onCreate(config)
        Adjust.trackEvent(AdjustEvent(""))
    }

    private fun initLanguage() {
        applicationScope.launchSafety {
            if (KVStore.speakLanguage.code.isEmpty()) {
                KVStore.speakLanguage =
                    getLanguages().find { it.code.lowercase() == deviceLanguage.lowercase() }
                        ?: Language(
                            "en", "English"
                        )
            }
        }
    }

    override suspend fun onProductPurchase(purchase: Purchase, params: PurchaseParams) {
        runCatching {
            if (params.skuId.isEmpty()) {
                return@runCatching
            }
            recordPaySuccess(params.skuId, params.price.toDouble())
            delay(1000)
            systemService.orderSignVerify(
                mapOf(
                    "sku_id" to params.skuId,
                    "purchases_token" to purchase.purchaseToken,
                    "package" to packageName,
                    "type" to 0
                )
            )
            UserManager.refreshAuthSync()
        }.onFailure {
            it.printStackTrace()
            UserManager.refreshAuth()
        }
    }

    private fun recordPaySuccess(skuId: String, price: Double) {
        val event = AdjustEvent("")
        event.setRevenue(price, "USD")
        Adjust.trackEvent(event)
        val bundle = Bundle()
        val transactionId = System.currentTimeMillis().toString()
        bundle.putString(FirebaseAnalytics.Param.TRANSACTION_ID, transactionId)
        bundle.putString(FirebaseAnalytics.Param.CURRENCY, "USD")
        bundle.putDouble(FirebaseAnalytics.Param.VALUE, price)

        val item1 = Bundle()
        item1.putString(FirebaseAnalytics.Param.ITEM_ID, skuId)
        item1.putString(FirebaseAnalytics.Param.ITEM_NAME, skuId)
        val items = ArrayList<Bundle>()
        items.add(item1)
        bundle.putParcelableArrayList(FirebaseAnalytics.Param.ITEMS, items);
        val firebaseAnalytics = FirebaseAnalytics.getInstance(this)
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.PURCHASE, bundle)
        runCatching {
            val logger = AppEventsLogger.newLogger(this)
            logger.logPurchase(BigDecimal(price), Currency.getInstance("USD"))
        }
    }

    override fun newImageLoader(): ImageLoader {
        val imageLoader = ImageLoader.Builder(this)
        val newBuilder = ComponentRegistry().newBuilder()
        if (KVStore.enableGif) {
            if (Build.VERSION.SDK_INT >= 28) {
                newBuilder.add(ImageDecoderDecoder.Factory())
            } else {
                newBuilder.add(GifDecoder.Factory())
            }
        }
        val componentRegistry: ComponentRegistry = newBuilder.build()
        imageLoader.components(componentRegistry)
        imageLoader.memoryCache(MemoryCache.Builder(this).maxSizePercent(0.31).build())
        val cacheFile = File(cacheDir, "lovely_cache_image")
        val stats = StatFs(cacheFile.apply { mkdir() }.absolutePath)
        val size = stats.blockCountLong * stats.blockSizeLong
        imageLoader.diskCache(
            DiskCache.Builder().directory(cacheFile).maxSizePercent(1.0).maximumMaxSizeBytes(size)
                .build()
        )
        return imageLoader.build()
    }
}

object LifecycleApplication : Application.ActivityLifecycleCallbacks {
    private val activityStack = Stack<Activity>()
    private var activityCounter = 0


    fun finishAll() = run {
        while (activityStack.isNotEmpty()) {
            activityStack.pop()?.finish()
        }
    }

    override fun onActivityCreated(p0: Activity, p1: Bundle?) {
        activityStack.push(p0)
    }

    override fun onActivityStarted(p0: Activity) {
        activityCounter++;
    }

    override fun onActivityResumed(p0: Activity) {
        Adjust.onResume()
    }

    override fun onActivityPaused(p0: Activity) {
        Adjust.onPause()
    }

    override fun onActivityStopped(p0: Activity) {
        activityCounter--;
    }

    override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {

    }

    override fun onActivityDestroyed(p0: Activity) {
        activityStack.remove(p0)
    }

    fun getAppFrontRunning(): Boolean {
        return activityCounter > 0
    }
}